<template>
  <div>
    <el-descriptions title="基本信息" direction="vertical" :column="4" border>
      <template slot="extra">
        <el-button type="primary" size="small" @click="handleEdit" plain
          >修改信息</el-button
        >
        <el-button type="success" size="small" @click="handleEditPwd" plain
          >修改密码</el-button
        >
      </template>
      <el-descriptions-item label="头像">
        <img
          v-if="user.headImg"
          :src="user.headImg"
          class="avatar"
          style="width: 80px; height: 80px"
        />
      </el-descriptions-item>
      <el-descriptions-item label="用户名">{{
        user.userName
      }}</el-descriptions-item>
      <el-descriptions-item label="姓名">{{
        user.nickName
      }}</el-descriptions-item>
      <el-descriptions-item label="手机号">{{ user.tel }}</el-descriptions-item>
      <el-descriptions-item label="账号创建时间">{{
        user.creatTime
      }}</el-descriptions-item>
    </el-descriptions>
    <el-descriptions title="企业信息" direction="vertical" :column="4" border>
      <el-descriptions-item label="工号">{{ emp.workNo }}</el-descriptions-item>
      <el-descriptions-item label="部门名称">{{
        emp.deptName
      }}</el-descriptions-item>
      <el-descriptions-item label="职位名称">{{
        emp.jobName
      }}</el-descriptions-item>
      <el-descriptions-item label="入职时间">{{
        emp.hiredate
      }}</el-descriptions-item>
    </el-descriptions>

    <!-- -------------------修改dialog---------------------- -->
    <el-dialog title="修改用户" :visible.sync="dialog.updateShow" width="30%">
      <el-form :model="updateForm" :rules="updateRules" status-icon ref="updateForm">
        <el-form-item label="用户头像" :label-width="formLabelWidth">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:9000/uploadoss"
            name="file"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="updateForm.headImg"
              :src="updateForm.headImg"
              style="width: 100px; height: 100px"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="用户名" :label-width="formLabelWidth" prop="userName">
          <el-input
            v-model="updateForm.userName"
            autocomplete="off"
            placeholder="请输入账号"
          ></el-input>
        </el-form-item>
        <el-form-item label="生日" :label-width="formLabelWidth">
          <el-date-picker
            v-model="updateForm.creatTime"
            type="date"
            placeholder="选择日期"
            style="width: 100%"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item label="id" :label-width="formLabelWidth" hidden>
          <el-input v-model="updateForm.userId"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog.updateShow = false">取 消</el-button>
        <el-button type="primary" @click="updateInfo">确 定</el-button>
      </div>
    </el-dialog>

    <!-- -------------------修改密码dialog---------------------- -->
    <el-dialog title="修改密码" :visible.sync="dialog.changePwd" width="30%">
      <el-form :model="pwdForm" :rules="rules" status-icon ref="pwdForm">
        <el-form-item
          label="原密码"
          :label-width="formLabelWidth"
          prop="oldPwd"
        >
          <el-input
            v-model="pwdForm.oldPwd"
            autocomplete="off"
            show-password
            placeholder="请输入原密码"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="新密码"
          :label-width="formLabelWidth"
          prop="newPwd"
        >
          <el-input
            v-model="pwdForm.newPwd"
            autocomplete="off"
            show-password
            placeholder="请输入新密码"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="确认密码"
          :label-width="formLabelWidth"
          prop="newPwdConfirm"
        >
          <el-input
            v-model="pwdForm.newPwdConfirm"
            autocomplete="off"
            show-password
            placeholder="请确认新密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="id" :label-width="formLabelWidth" hidden>
          <el-input v-model="pwdForm.userId"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog.changePwd = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('pwdForm')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    var validateOldPass = (rule, value, callback) => {
      this.$axios
        .post("/users/judgment", {
          userName: this.user.userName,
          password: value
        })
        .then(res => {
          if (res.data.code == 200) {
            callback();
          } else {
            callback(new Error("原密码错误"));
          }
        });
    };
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.pwdForm.newPwdConfirm !== "") {
          this.$refs.pwdForm.validateField("newPwdConfirm");
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.pwdForm.newPwd) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      matches: false,
      pwdForm: {
        userId: "",
        oldPwd: "",
        newPwd: "",
        newPwdConfirm: ""
      },
      updateRules: {
        userName: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" }
        ],
      },
      rules: {
        oldPwd: [{ validator: validateOldPass, trigger: "blur" }],
        newPwd: [
          { validator: validatePass, trigger: "blur" },
          { pattern: '^(?![a-zA-Z]+$)(?!\d+$)(?![^\da-zA-Z\s]+$).{6,18}$', message: '由6-18位字母、数字、特殊字符，任意2种'}
      ],
        newPwdConfirm: [{ validator: validatePass2, trigger: "blur" }]
      },
      updateForm: {},
      formLabelWidth: "120px",
      dialog: {
        updateShow: false,
        changePwd: false
      },
      user: JSON.parse(sessionStorage.getItem("user")),
      emp: {},
      imageUrl: ""
    };
  },
  methods: {
    handleEditPwd() {
      this.$axios
        .post("/users/queryInfo", {
          userId: this.user.userId
        })
        .then(res => {
          this.dialog.changePwd = true;
          this.pwdForm.userId = this.user.userId;
        });
    },
    handleEdit() {
      this.$axios
        .post("/users/queryInfo", {
          userId: this.user.userId
        })
        .then(res => {
          this.dialog.updateShow = true;
          this.updateForm = res.data.data.user;
        });
    },
    updateInfo() {
      this.$axios.put("/users", this.updateForm).then(res => {
        if (res.data.code == 200) {
          this.$message.success("更新成功");
        } else {
          this.$message.error("异常");
        }
        this.dialog.updateShow = false;
      });
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.updatePwd();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    updatePwd() {
      this.$axios.put("/users/pwd", this.pwdForm).then(res => {
        if (res.data.code == 200) {
          this.$message.success("更新成功");
        } else {
          this.$message.error("异常");
        }
        this.dialog.changePwd = false;
      });
    },
    loadUserInfo() {
      this.$axios
        .post("/users/queryInfo", {
          userId: this.user.userId,
          workNo: this.user.workNo
        })
        .then(res => {
          if (res.data.code == 200) {
            this.user = res.data.data.user;
            this.emp = res.data.data.emp;
          } else {
            this.$message({
              message: res.data.message,
              type: "error"
            });
          }
        })
        .catch(err => {
          console.error(err);
        });
    },
    handleAvatarSuccess(res, file) {
      if (res.code == 200) {
        this.updateForm.headImg = res.message;
        sessionStorage.setItem("user", JSON.stringify(this.updateForm));
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    }
  },
  mounted() {
    this.loadUserInfo();
  }
};
</script>
